﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DBWTProject.models;
using System.Diagnostics;
using DBWTProject.persistence;

namespace DBWTProject.useradministration
{
    public partial class UserProfile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            User user = (User)Session[Constants.SESSIONVAR_CURRENTUSER];
            if (user == null)
            {//nicht eingeloggt
                Response.Redirect("/");
                return;
            }

            if (!IsPostBack)//GET-Request. Post wäre Änderungsevent.
            {
                txbFullname.Text = user.FullName;
                txbUser.Text = user.Name;
            }
        }

        protected void btnSubmitNames_Click(object sender, EventArgs e)
        {
            Debug.WriteLine(txbUser.Text);
            Debug.WriteLine(txbFullname.Text);

            User user = (User)Session[Constants.SESSIONVAR_CURRENTUSER];
            user.Name = txbUser.Text;
            user.FullName = txbFullname.Text;

            saveToDB(user);

            Response.Redirect(Request.Url.ToString());//Refresh Login-Message im Header
        }

        protected void btnSubmitPassword_Click(object sender, EventArgs e)
        {
            User user = (User)Session[Constants.SESSIONVAR_CURRENTUSER];
            string pw = txbPwOld.Text;
            string pwNew = txbPwNew.Text;
            string pwNewRepeat = txbPwNewRepeat.Text;

            if (String.IsNullOrEmpty(pwNew.Trim()) || String.IsNullOrEmpty(pwNewRepeat.Trim()) )
            {
                lblError.Text = "Please fill out all password text fields.";
                return;
            }
            if (pwNew != pwNewRepeat)
            {
                lblError.Text = "You inserted two different strings for the new password";
                return;
            }

            if (pw != user.Password)
            {
                lblError.Text = "Your old password was not correct.";
                return;
            }

            lblError.Text = "";
            user.Password = pwNew;
            saveToDB(user);
        }

        private void saveToDB(User user)
        {
            RouteDAO.UpdateUser(user.ID, user);
        }


    }
}